<template>
    <div @click.self="clickPop" class="Corporate">
        <div @click.self="clickPop" class="CorporateBox">
            <div @click="clickPop" class="left">
                <Left v-bind:active-entry="gc"
                      v-on:click-item="clickItem"></Left>
            </div>
            <div @click.self="clickPop" class="right">
                <div @click="clickPop" class="rightTop">
                    <div class="comTLeft">
                        <div>企业顾问</div>
                        <div class="comTalent"></div>
                    </div>
                </div>
                <div @click="clickPop" class="rightTop CorporateR CorpH">
                    <div class="name">{{adviser.name}}</div>
                    <div class="telphone">{{adviser.phone}}</div>
                    <div class="time">{{adviser.workTime}}</div>
                </div>
                <!--内容-->
                <div @click="clickPop" style="height: calc(100% - 240px);width: 100%;">
                    <el-scrollbar
                            style="height: 100%;width: 100%;"
                            ref="myScrollbar">
                        <div class="record_list">
                            <RecordItem v-for="(t,i) in recordCache" :key="i" :record="t"></RecordItem>
                        </div>
                    </el-scrollbar>
                </div>
                <!--底部-->
                <div @click.self="clickPop"
                     style="width: 100%; height: 140px;border-top: 2px solid #F7F7F7;position: absolute;bottom: 0;">
                    <!--发送职位-->
                    <div style="font-size:13px;display: flex;flex-direction: row;align-items: center;position: absolute;top: 5px;right: 50px;cursor: default;"
                         @click="doJob">
                        <div :class="{'icon_black':!popover,'icon_blue':popover}"></div>
                        <div :class="{'fontColor':popover,'normal_send_color':!popover}">发送职位
                        </div>
                    </div>
                    <textarea @click="clickPop" @keyup.ctrl.enter.exact="addNewLine" @keyup.enter.exact="doSend"
                              maxlength="200"
                              class="input_text_cls"
                              placeholder="输入文字，最多200字"
                              v-model="currentInput"></textarea>
                    <div @click="clickPop"
                         style="font-size:12px;color:#999;position:absolute;bottom: 15px;right: 130px;">
                        按Ctrl+Enter换行，Enter发送
                    </div>
                    <div class="btn" @click="doSend">发送</div>
                </div>
                <!--点击发送职位弹出的内容-->
                <div class="popoverBox" v-show="popover">
                    <!--职位列表-->
                    <el-scrollbar style="margin-left:20px;margin-top:10px;height: 65%;">
                        <div class="job_list_cls">
                            <div v-for="(t,i) in jobCache" class="job_box_cls"
                                 style="width:200px;height:50px;display:flex;align-items:center;"
                                 @click="clickJobBox(i)">
                                <p @click="clickJob(i)"
                                   :class="{'job_normal_cls':i!==communication.jobActive,'job_active_cls':i===communication.jobActive}">
                                    {{t.name}}</p>
                                <img src="@/assets/img/communication/next.png" alt="查看人才">
                            </div>
                        </div>
                    </el-scrollbar>
                    <!--人才列表-->
                    <el-scrollbar style="margin-top:10px;margin-bottom: 35px;">
                        <div class="talent_list_cls">
                            <MsgTalentItem style="background:rgba(247,247,247,1);margin-top:10px;margin-bottom:10px"
                                           v-for="(t,i) in talentCache" :key="i"
                                           :item="t"
                                           @click="clickTalent(i)"
                            ></MsgTalentItem>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
  import Left from '../Left'
  import _subject from '../../assets/utils/subject'
  import _g from '../../assets/utils/global'
  import * as _ from 'underscore'
  import RecordItem from '../communication/chatWindow/RecordItem'
  import MsgTalentItem from './MsgTalentItem'
  import comm from '../../assets/utils/comm'

  export default {
    name: 'Corporate',
    props: {
      side: {
        type: String,
        default: 'company'
      }
    },
    computed: {
      recordCache() {
        //显示时间
        for (let i = 1; i < this.communication.records.length; i++) {
          const last = this.communication.records[i - 1]
          const current = this.communication.records[i]
          current.showTimeQ = current.time - last.time > 3 * 60 * 1000
        }
        //显示头像
        _.each(this.communication.records, t => {
          t.icon = t.meQ ? _subject.getCompanyIcon() : comm.toIcon
        })
        return this.communication.records
      },
      jobCache() {
        this.communication.jobs = _.map(this.serverJobs, t => {
          return {
            id: t.id,
            name: t.jobName,
            salary: {
              a: (t.tax === 0 ? '税前' : '税后') + t.salaryPerMonthLow + '-' + t.salaryPeMonthHigh + 'W',
              b: '/' + t.salaryCount + '年'
            },
            city: t.city,
            workTime: t.workTimeStr,
            license: t.licenseTypeStr,
            num: t.nums,
            publishTime: t.realseTime
          }
        })
        return this.communication.jobs
      },
      talentCache() {
        if (this.communication.jobActive > -1) {
          this.communication.talents = _.map(
            _.filter(this.serverJobs[this.communication.jobActive].resumeList,
              t => {
                return t.json
              }),
            t => {
              console.log('tttt', t)
              let json = JSON.parse(t.json)
              console.log('talent', json)
              if (json && json.talent) {
                const talent = json.talent
                const zero = function(t) {
                  if (t) {
                    return t
                  } else {
                    return 0
                  }
                }
                return {
                  name: talent.talentName,
                  image: talent.image,
                  city: talent.workCity,
                  age: talent.talentAge + '岁',
                  salary: {
                    a: (t.tax === 0 ? '税前' : '税后') + zero(t.salaryPerMonth) + 'W',
                    b: '/' + zero(t.monthCount) + '年'
                  },
                  license: json.licenseList,
                  workTime: talent.workDay + '年',
                  workState: talent.jobStateContent
                }
              } else {
                return {}
              }
            })
        } else {
          this.communication.talents = []
        }
        return this.communication.talents
      }
    },
    data() {
      return {
        gc: { g: 0, c: 0 },
        popImg: require('@/assets/img/communication/pop_bg.png'),
        userImg: require('@/assets/img/1.jpg'),
        popover: false,
        contjob: false,
        adviser: { name: '顾问姓名', phone: '顾问电话', workTime: '上班时间：9:00-17:00' },
        currentInput: '',
        wsSub: null,
        serverJobs: [],
        communication: {
          commId: 0,
          toId: 0,
          records: [],
          jobActive: -1,
          jobs: [
            { name: '职位名称' }
          ],
          talentActive: -1,
          talents: [
            { name: '职位名称职位名称职位名称' }
          ],
          page: {
            size: 10,
            current: 0,
            all: 0,
            total: 0,
            lastHeight: 0
          }
        }
      }
    },
    methods: {
      loadAdviser() {
        _g.apiPost('/company/selectPlatformByComId.do', {})
          .then(res => {
            if (res && res.status === 0) {
              let t = res.data
              if (t) {
                this.adviser.name = '顾问姓名：' + (t.nickName ? t.nickName : '未知')
                this.adviser.phone = '顾问电话：' + (t.phone ? t.phone : '未知')
                this.adviser.workTime = '上班时间：' + (t.workTime ? t.workTime : '未知')
              }
            }
          })
      },
      clickPop() {
        this.popover = false
      },
      getNewMessage(commId, unread) {
        this.$emit('new-msg', commId, unread)
      },
      scrollDown() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      onScrollTop() {
        this.loadRecords()
      },
      scrollPercent() {
        //异步滚动
        setTimeout(() => {
          this.$refs['myScrollbar'].wrap.scrollTop = this.$refs['myScrollbar'].wrap.scrollHeight - this.communication.page.lastHeight
          this.communication.page.lastHeight = this.$refs['myScrollbar'].wrap.scrollHeight
        }, 1)
      },
      clickTalent(i) {
        this.communication.talentActive = i
        let talent = this.communication.talents[i]
        talent.jobName = this.communication.jobs[this.communication.jobActive].name
        console.log('active talent', talent)
        this.sendContent(JSON.stringify(talent), 4)
        this.scrollDown()
        this.popover = false
      },
      clickJobBox(i) {
        this.communication.jobActive = i
      },
      clickJob(i) {
        this.sendContent(JSON.stringify(this.communication.jobs[i]), 5)
        this.scrollDown()
        this.popover = false
      },
      doJob() {
        this.icon = !this.icon
        this.popover = !this.popover
      },
      getSysMsg(type, text) {
        if (type === 1) {
          switch (text) {
            case '拒绝':
              return '人才已拒绝您的入职邀请'
            case '接受':
              return '人才已接受您的入职邀请'
          }
        }
        return text
      },
      //加载职位
      loadJobs() {
        _g.apiPost('/company/selectJobResumeInfo.do', {})
          .then(res => {
            if (res && res.status === 0) {
              console.log('company jobs', res)
              this.serverJobs = res.data
            }
          })
      },
      loadRecords() {
        //到达最后一页，不再加载
        if (this.communication.page.current > 0 && this.communication.page.current === this.communication.page.all) {
          return
        }
        _g.apiPost('/company/selectPlafromInfoAndChat.do', {
          currPageNo: this.communication.page.current + 1,
          pageSize: this.communication.page.size
        }).then(res => {
          if (res && res.status === 0) {
            //沟通id
            this.communication.commId = res.data.comId
            //平台用户
            this.communication.toId = res.data.platformUser.id
            comm.toIcon = res.data.platformUser.headImage
            //分页信息
            const page = res.data.pageInfo
            if (page) {
              this.communication.page.total = page.total
              this.communication.page.all = page.pages
              if (page.list.length > 0) {
                this.communication.page.current = page.pageNum
                let temp = _.map(page.list, t => {
                  const o = JSON.parse(t.content)
                  const state = Number(o.send_state)
                  let type = state
                  let content = this.getSysMsg(state, o.content)
                  const time = Date.parse(t.time)
                  return {
                    image: o.head,
                    showTimeQ: false,
                    meQ: o.mainCom === this.side,
                    content: content,
                    type: type,
                    time: time,
                    job: type === 5 ? JSON.parse(content) : {},
                    talent: type === 4 ? JSON.parse(content) : {},
                    hello: type === 6 ? content : {}
                  }
                })
                temp = _.sortBy(temp, t => {
                  return t.time
                })
                if (this.communication.page.current === 1) {
                  this.communication.records = temp
                  this.scrollDown()
                } else {
                  this.communication.records = temp.concat(this.communication.records)
                  this.scrollPercent()
                }
              } else {
                this.communication.page.current -= 1
              }
            }
          }
        })
      },
      sendContent(text, type) {
        const str = {
          'toCom': 'platform',
          'toUserId': String(this.communication.toId),
          'comid': String(this.communication.commId),
          'type': 'SINGLE_SENDING',
          'content': text,
          'mainUserId': _subject.getCompanyId(),
          'mainCom': 'company',
          'send_state': String(type)
        }
        console.log('send ws', str)
        _subject.ws.next(str)
        //添加到本地记录
        this.communication.records.push({
          type: type,
          talent: type === 4 ? JSON.parse(text) : {},
          job: type === 5 ? JSON.parse(text) : {},
          hello: type === 6 ? text : {},
          content: text,
          meQ: true,
          time: new Date().format('yyyy-MM-dd hh:mm:ss')
        })
        this.scrollDown()
      },
      addNewLine() {
        this.currentInput += '\n'
      },
      doSend() {
        this.icon = false
        this.contjob = true
        this.popover = false
        let trim = this.currentInput.trim()
        if (trim) {
          this.sendContent(trim.replace(/\n/g, '<br/>'), 0)
          this.currentInput = ''
        }
        this.scrollDown()
        this.currentInput = ''
      },
      clickItem: function(g, c) {
        this.gc = { g: g, c: c }
        _g.getCache().gc = this.gc
        if (g == 0 && c == 0) {
          this.$router.push({ path: '/resume' })
        } else if (g == 0 && c == 1) {
          this.$router.push({ path: '/resume' })
        } else if (g == 1 && c == 0) {
          this.$router.push({ path: '/communication' })
        } else if (g == 2 && c == 0) {
          this.$router.push({ path: '/resume' })
        } else if (g == 2 && c == 1) {
          this.$router.push({ path: '/resume' })
        } else if (g == 2 && c == 2) {
          this.$router.push({ path: '/resume' })
        }
      }
    }
    ,
    components: {
      MsgTalentItem,
      RecordItem,
      Left
    }
    ,
    mounted() {
      this.gc = _g.getCache().gc
      this.loadAdviser()
      //消息记录滑到顶部刷新
      this.$refs['myScrollbar'].wrap.onscroll = e => {
        if (e.target.scrollTop === 0) {
          this.onScrollTop()
        }
      }
    },
    created() {
      this.loadRecords()
      this.loadJobs()
      let self = this
      this.wsSub = _subject.ws.subscribe({
        next(t) {
          if (t.status === 200) {
            let m = t.data.type
            if (m === 'SINGLE_SENDING') {
              let commId = t.data.comid
              let mainId = t.data.mainUserId
              let toId = t.data.toUserId//对方发送的消息
              //通知收到父组件消息
              self.getNewMessage(Number(t.data.comid), Number(t.data.unread))
              if (commId === String(self.communication.commId) && toId === String(_subject.getCompanyId()) && mainId === String(self.communication.toId)) {
                const type = Number(t.data.send_state)
                const content = self.getSysMsg(type, t.data.content)
                self.communication.records.push({
                  type: type,
                  content: content,
                  meQ: false,
                  time: new Date().format('yyyy-MM-dd hh:mm:ss'),
                  job: type === 5 ? JSON.parse(content) : {},
                  talent: type === 4 ? JSON.parse(content) : {},
                  hello: type === 6 ? content : {}
                })
              }
              self.scrollDown()
            }
          } else if (t.status === -1) {
            _g.message('对方不在线，可能无法立即回复您', 'warning')
          }
        }
      })
    },
    destroyed() {
      if (this.wsSub) {
        this.wsSub.unsubscribe()
      }
    }
  }
</script>

<style lang="scss" scoped>
    .Corporate {
        width: 100%;
        height: 100%;
        display: flex;
        /*flex-direction: row;*/
        /*border: 2px solid red;*/
    }

    .CorporateBox {
        width: 1200px;
        height: 100%;
        /*border: 2px solid yellow;*/
        margin: 0 auto;
        padding-top: 20px;
        display: flex;
        flex-direction: row;
    }

    /*.left {*/
    /*width: 200px;*/
    /*height: 100px;*/
    /*border: 1px solid pink;*/
    /*}*/
    .right {
        width: 980px;
        height: calc(100vh - 125px);
        background-color: white;
        margin-left: 19px;

        position: relative;
        /*border: 1px solid red;*/
    }

    .rightTop {
        width: 100%;
        height: 50px;
        /*border: 1px solid pink;*/
    }

    .comTLeft {
        line-height: 40px;
        margin-left: 50px;
        font-size: 20px;
        color: #333;
    }

    .comTLeft > div:nth-child(1) {
        line-height: 50px;
    }

    .comTLeft > div:nth-child(2) {
        margin-top: -6px;
        margin-left: 14px;
    }

    .comTalent {
        width: 50px;
        height: 3px;
        /*background-color: #FF7300;*/
        text-align: center;
    }

    .CorporateR {
        display: flex;
        flex-direction: row;
        background-color: #F7FDFF;
        color: #666;
        font-size: 13px;
    }

    .CorpH {
        line-height: 50px;
    }

    .name {
        margin-left: 50px;
    }

    .telphone {
        margin-left: 39px;
    }

    .time {
        margin-left: 40px;
    }

    .CorporateT {
        width: 100%;

        margin-top: 30px;
        color: #999;
        font-size: 14px;
        text-align: center;
    }

    .content {
        width: 100%;
        height: 100%;
        position: relative;
        border-bottom: 2px solid rgba(247, 247, 247, 1);
        transform: translate(-50%, -32%);
        /*outline: red solid 2px;*/
    }


    .icon_black, .icon_blue {
        width: 14px;
        height: 12px;
        margin-right: 8px;
        background: url("../../assets/img/communication/job_black.png") no-repeat;
        background-size: cover;
    }

    .icon_blue {
        background: url("../../assets/img/communication/job_blue.png") no-repeat;
        background-size: cover;
    }

    .fontColor {
        color: #4ab0cf;
    }

    .normal_send_text {
        color: #999;
    }

    .fontCont {
        margin-top: 52px;
        margin-left: 50px;
        font-size: 14px;
        color: #333;
    }

    .btn {
        width: 72px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        border: 1px solid #ccc;
        border-radius: 18px;
        color: #ccc;
        font-size: 13px;
        position: absolute;
        bottom: 10px;
        right: 50px;
        cursor: default;
    }

    /*-----------------弹出框-----------------------*/
    .popover {
        width: 802px;
        height: 605px;
        /*border: 1px solid pink;*/
        position: absolute;
        right: 0;
        bottom: 17px;
        z-index: 2;
        font-size: 14px;
        color: #333;
        display: flex;
        flex-direction: row;
    }

    .popImg {
        width: 100%;
        height: 100%;

        img {
            width: 100%;
        }
    }

    .popLeft {
        width: 200px;
    }

    .jobName, .jobNameBg {
        width: 200px;
        height: 50px;
        line-height: 50px;
        display: flex;
        flex-direction: row;
        margin-left: 10px;
        margin-top: 10px;
        margin-bottom: 5px;
        background-color: white;
        /*border: 1px solid pink;*/
    }

    .empty {
        width: 3px;
        height: 30px;
        background-color: #FF7300;
        margin-top: 10px;
        margin-right: 17px;
    }

    .jobfont {
        color: #DD3A31;
    }

    .fontS {
        width: 168px;
        height: 15px;
        margin-left: 20px;
        margin-top: 18px;
        font-size: 14px;
        color: #333;
        line-height: 0;


    }

    .jobNameBg {
        background-color: #FAFAFA;
    }

    .jobS {
        width: 168px;
        height: 18px;
        font-size: 14px;
        color: #333;
        padding-top: 7px;
        /*border: 1px solid pink;*/
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap
    }

    /*-------------------popRight------------------------*/
    .popRight {
        width: 560px;
        padding-top: 21px;
        margin-left: 20px;
        /*border: 1px solid pink;*/
    }

    .popRightBox {
        width: 558px;
        height: 80px;
        background-color: #F7F7F7;
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
    }

    .userImg {
        width: 51px;
        height: 51px;
        margin-left: 20px;
        padding-top: 14px;

        img {
            width: 100%;
        }
    }

    .popR_RBox {
        margin-left: 20px;
        margin-top: 15px;
    }

    .popR_R {
        display: flex;
        flex-direction: row;
        font-size: 14px;
    }

    .marginT {
        margin-top: 10px;
    }

    .fontSize {
        font-size: 18px;
    }

    .fontW {
        font-weight: bold;
    }

    .fontW > div {
        margin-right: 20px;
    }

    .fontW > div:nth-child(2) {
        margin-top: 3px;
    }

    .fontW > div:nth-child(3) {
        margin-top: 3px;
    }

    .fontSize1 {
        font-size: 14px;
        color: #999;
    }

    .fontSize1 > div {
        font-size: 14px;
        color: #999;
        border-right: 1px solid #999;
        padding-right: 10px;
        margin-right: 10px;
    }

    .fontSize1 > div:nth-child(4) {
        border-right: none;
    }

    /*------------------点击发送之后的内容-----------------------------*/
    .contjob {
        display: flex;
        flex-direction: row;
        position: absolute;
        right: 0;
        margin-bottom: 10px;
    }

    .contjobL {
        width: 760px;
        height: 80px;
        background-color: #F7F7F7;
        border-radius: 20px;
        display: flex;
        flex-direction: row;
    }

    .contjobImg {
        width: 25px;
        height: 25px;
        border: 1px solid white;
        border-radius: 50%;
        overflow: hidden;
        margin-right: 50px;
        margin-left: 10px;
    }

    .contjobL_box {
        width: 200px;
        height: 80px;
    }

    .contjobL_box > .fontS {
        margin-top: 34px;
    }

    .contjobL_R {
        width: 560px;
        height: 80px;
        border-radius: 0 20px 20px 0;
        background-color: #F7F7F7;
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
    }

    .record_list {
        width: 100%;
        min-height: 100%;
    }

    .popoverBox {
        width: 802px;
        height: 605px;

        position: absolute;
        bottom: 120px;
        right: 0;

        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        background: url('../../assets/img/communication/pop_bg.png') center;
        background-size: cover;
    }

    .job_list_cls {
        /*border: 1px solid green;*/
        background: white;
    }

    .job_box_cls {
        background: rgba(243, 243, 247, 1);
        border: 1px solid rgba(250, 250, 250, 1);
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding-right: 15px;
    }

    .job_normal_cls {
        padding-left: 20px;
        border-left: 2px transparent solid;
    }

    .job_normal_cls:hover {
        color: rgba(240, 147, 56, 1);
    }

    .job_active_cls {
        padding-left: 20px;
        border-left: 2px rgba(240, 147, 56, 1) solid;
    }

    .job_active_cls:hover {
        color: rgba(240, 147, 56, 1);
    }

    .talent_list_cls {
        background: white;
    }

    .input_text_cls {


        resize: none;

        width: calc(100% - 65px);
        height: calc(100% - 70px);

        padding: 0;

        margin-top: 30px;
        margin-left: 15px;

        font-size: 13px;

        border: none;


    }
</style>
